package com.hll.fliter;

import javax.servlet.*;
import java.io.IOException;

/**
 * @program: JavaWebDemo-01
 * @description:
 * @author: Mr.Hu
 * @create: 2021-03-06 17:34
 */
public class Fliter implements Filter {

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
    System.out.println("初始化过滤器");
    // tomcat启动时初始化
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    request.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");
    response.setCharacterEncoding("utf-8");
    // 不管是客户端发过来的request还是服务器发过去的response,如果是过滤范围内，就需要经过这层Filter
    System.out.println("过滤前");
    chain.doFilter(request, response); // 如果不写的话，请求或回应会终止于此，不会转交给servlet或client
    System.out.println("过滤后");
  }

  @Override
  public void destroy() {
    System.out.println("摧毁过滤器");
    // tomcat关闭时销毁
  }
}
